package gops

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// WechatSendMarkdownMessage 发送企业微信 Markdown 消息
func WechatSendMarkdownMessage(token string, markdownContent string) error {
	webhookURL := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s", token)
	message := map[string]any{
		"msgtype": "markdown",
		"markdown": map[string]string{
			"content": markdownContent,
		},
	}
	messageBytes, err := json.Marshal(message)
	if err != nil {
		return err
	}
	resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(messageBytes))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var result map[string]any
	err = json.Unmarshal(body, &result)
	if err != nil {
		return err
	}
	if result["errcode"].(float64) != 0 {
		return fmt.Errorf("send message error: %s", result["errmsg"].(string))
	}
	return nil
}
